OPC Studio User's Guide and Reference
Writing Attributes of OPC UA Nodes
View with Navigation Tools
Concepts > OPC Data Client Concepts > OPC Data Client Development Models > Imperative Programming Model > Imperative Programming Model for OPC Data (Classic and UA) > Modifying Information (OPC Data) > Writing Attributes of OPC UA Nodes
In This Topic

A single node and attribute

If you want to write a data value into an attribute of a specific node in OPC UA, call the WriteValue method, passing it the data value you want to write, arguments for endpoint descriptor, node ID, and an optional data type.

One-time write:

.NET

// This example shows how to write a value into a single node.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in C# on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples._EasyUAClient
{
    partial class WriteValue
    {
        public static void Main1()
        {
            UAEndpointDescriptor endpointDescriptor =
                "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            // or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
            // or "https://opcua.demo-this.com:51212/UA/SampleServer/"

            // Instantiate the client object.
            var client = new EasyUAClient();

            Console.WriteLine("Modifying value of a node...");
            try
            {
                client.WriteValue(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10221", 12345);
            }
            catch (UAException uaException)
            {
                Console.WriteLine($"*** Failure: {uaException.GetBaseException().Message}");
                return;
            }

            Console.WriteLine("Finished.");
        }
    }
}

COM

// This example shows how to write a value into a single node.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

#include "stdafx.h"    // Includes "QuickOpc.h", and other commonly used files
#include "WriteValue.h"

namespace _EasyUAClient
{
    void WriteValue::Main()
    {
        // Initialize the COM library
        CoInitializeEx(NULL, COINIT_MULTITHREADED);
        {
            // Instantiate the client object
            _EasyUAClientPtr ClientPtr(__uuidof(EasyUAClient));

            // Perform the operation
            ClientPtr->WriteValue(
                //L"http://opcua.demo-this.com:51211/UA/SampleServer", 
                L"opc.tcp://opcua.demo-this.com:51210/UA/SampleServer",
                L"nsu=http://test.org/UA/Data/ ;i=10221",
                12345);
        }
         // Release all interface pointers BEFORE calling CoUninitialize()
        CoUninitialize();
    }
}

Python

# This example shows how to write a value into a single node.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
# a commercial license in order to use Online Forums, and we reply to every post.
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.OperationModel import *


# Instantiate the client object.
client = EasyUAClient()

# Perform the operation.
try:
    IEasyUAClientExtension.WriteValue(client,
        UAEndpointDescriptor('opc.tcp://opcua.demo-this.com:51210/UA/SampleServer'),
        UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10221'),
        12345)
except UAException as uaException:
    print('*** Failure: ' + uaException.GetBaseException().Message)
    exit()

print('Finished.')

Incrementing write:

.NET

// This example shows how to write an ever-incrementing value to an OPC UA variable.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in C# on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using System.Threading;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.AddressSpace;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples._EasyUAClient
{
    partial class WriteValue
    {
        public static void Incrementing()
        {
            UAEndpointDescriptor endpointDescriptor =
                "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            // or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
            // or "https://opcua.demo-this.com:51212/UA/SampleServer/"
            UANodeId nodeId = "nsu=http://test.org/UA/Data/ ;i=10221";
            // Example settings with Softing dataFEED OPC Suite: 
            //UAEndpointDescriptor endpointDescriptor =
            //    "opc.tcp://localhost:4980/Softing_dataFEED_OPC_Suite_Configuration1";
            //UANodeId nodeId = "nsu=Local%20Items ;s=Local Items.EAK_Test1.EAK_Testwert1_I4";

            // Instantiate the client object
            var client = new EasyUAClient();

            //
            int i = 0;

            do
            {
                Console.WriteLine($"@{DateTime.Now}: Writing {i}");
                try
                {
                    client.WriteValue(endpointDescriptor, nodeId, i);
                }
                catch (UAException uaException)
                {
                    Console.WriteLine("*** Failure: {0}", uaException.GetBaseException().Message);
                    return;
                }
                i = unchecked((i + 1) & 0x7FFFFFFF);
                Thread.Sleep(2 * 1000);
            } while (!Console.KeyAvailable);
        }
    }
}

COM

Rem This example shows how to write an ever-incrementing value to an OPC UA variable.
Rem
Rem Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
Rem OPC client and subscriber examples in VBScript on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-VBScript .
Rem Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
Rem a commercial license in order to use Online Forums, and we reply to every post.

Option Explicit

Const endpointDescriptorUrlString = "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer"
Const nodeIdExpandedText = "nsu=http://test.org/UA/Data/ ;i=10221"
' Example settings with Softing dataFEED OPC Suite: 
'Const endpointDescriptorUrlString = "opc.tcp://localhost:4980/Softing_dataFEED_OPC_Suite_Configuration1"
'Const nodeIdExpandedText = "nsu=Local%20Items ;s=Local Items.EAK_Test1.EAK_Testwert1_I4"

' Instantiate the client object
Dim Client: Set Client = CreateObject("OpcLabs.EasyOpc.UA.EasyUAClient")

' 
Dim i: i = 0

Do While True
    WScript.Echo "@" & Time & ": Writing " & i
    On Error Resume Next
    Client.WriteValue endpointDescriptorUrlString, nodeIdExpandedText, i
    If Err.Number <> 0 Then
        WScript.Echo "*** Failure: " & Err.Source & ": " & Err.Description
        WScript.Quit
    End If
    On Error Goto 0
    i = (i + 1) And &H7FFFFFFF
    WScript.Sleep 2*1000
Loop

When you specify individual arguments to the simplest overload of the WriteValue method, the method will write to the Value attribute of the node, and if the value type is an array, it will modify the whole contents of that array. If you want to write into a different attribute, or write only to a subset of an array, use one of the more complex overloads of the WriteValue method, such as with an argument of UAWriteValueArguments type, and fill this argument will all necessary information.

Multiple nodes or attributes

For writing data values into multiple OPC attributes (in the same or different nodes) in an efficient manner, call the WriteMultipleValues method. You pass in an array of UAWriteValueArgument objects, each specifying the location of OPC node, attribute, and the value to be written.

Example 1:

.NET

// This example shows how to write values into 3 nodes at once.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in C# on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples._EasyUAClient
{
    partial class WriteMultipleValues
    {
        public static void Main1()
        {
            UAEndpointDescriptor endpointDescriptor =
                "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            // or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
            // or "https://opcua.demo-this.com:51212/UA/SampleServer/"

            // Instantiate the client object
            var client = new EasyUAClient();

            // Modify value of a node
            client.WriteMultipleValues(new[]
                {
                    new UAWriteValueArguments(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10221", 23456),
                    new UAWriteValueArguments(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10226", 2.34567890),
                    new UAWriteValueArguments(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10227", "ABC")
                });
            // Production code would check the success of the operation. See separate example for that.
        }
    }
}

Python

# This example shows how to write values into 3 nodes at once.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
# a commercial license in order to use Online Forums, and we reply to every post.
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.OperationModel import *


endpointDescriptor = UAEndpointDescriptor('opc.tcp://opcua.demo-this.com:51210/UA/SampleServer')
# or 'http://opcua.demo-this.com:51211/UA/SampleServer' (currently not supported)
# or 'https://opcua.demo-this.com:51212/UA/SampleServer/'

# Instantiate the client object
client = EasyUAClient()

print('Modifying values of nodes...')
writeResultArray = IEasyUAClientExtension.WriteMultipleValues(client, [
    UAWriteValueArguments(endpointDescriptor, UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10221'), 23456),
    UAWriteValueArguments(endpointDescriptor, UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10226'), 2.34567890),
    UAWriteValueArguments(endpointDescriptor, UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10227'), 'ABC'),
    ])

# Production code would check the success of the operation. See separate example for that.

print()
print('Finished.')

Example 2:

The example above can be extended by properly testing for success of each operation, like this:

.NET

// This example shows how to write values into 3 nodes at once, test for success of each write and display the exception 
// message in case of failure.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// OPC client and subscriber examples in C# on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-CSharp .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

using System;
using OpcLabs.BaseLib.OperationModel;
using OpcLabs.EasyOpc.UA;
using OpcLabs.EasyOpc.UA.OperationModel;

namespace UADocExamples._EasyUAClient
{
    partial class WriteMultipleValues
    {
        public static void TestSuccess()
        {
            UAEndpointDescriptor endpointDescriptor =
                "opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            // or "http://opcua.demo-this.com:51211/UA/SampleServer" (currently not supported)
            // or "https://opcua.demo-this.com:51212/UA/SampleServer/"
            
            // Instantiate the client object.
            var client = new EasyUAClient();

            Console.WriteLine("Modifying values of nodes...");
            OperationResult[] operationResultArray = client.WriteMultipleValues(new[]
                {
                    new UAWriteValueArguments(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10221", 23456),
                    new UAWriteValueArguments(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;i=10226", 
                        "This string cannot be converted to Double"),
                    new UAWriteValueArguments(endpointDescriptor, "nsu=http://test.org/UA/Data/ ;s=UnknownNode", "ABC")
                });

            for (int i = 0; i < operationResultArray.Length; i++)
                if (operationResultArray[i].Succeeded)
                    Console.WriteLine($"Result {i}: success");
                else
                    Console.WriteLine($"Result {i}: {operationResultArray[i].Exception.GetBaseException().Message}");


            // Example output:
            //
            //Modifying values of nodes...
            //Result 0: success
            //Result 1: Input string was not in a correct format.
            //+ Attempting to change an object of type "System.String" to type "System.Double".
            //+ The specified original value (string) was "This string cannot be converted to Double".
            //+ The node descriptor used was: NodeId="nsu=http://test.org/UA/Data/ ;i=10226".
            //+ The client method called (or event/callback invoked) was 'WriteMultiple[3]'.
            //Result 2: The status of the OPC-UA attribute data is not Good. The actual status is 'BadNodeIdUnknown'.
            //+ During writing or method calls, readings may occur when value type is not specified.
            //+ The node descriptor used was: NodeId="nsu=http://test.org/UA/Data/ ;s=UnknownNode".
            //+ The client method called (or event/callback invoked) was 'WriteMultiple[3]'.
        }
    }
}

COM

// This example shows how to write values into 3 nodes at once, test for success of each write and display the exception
// message in case of failure.
//
// Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
// Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
// a commercial license in order to use Online Forums, and we reply to every post.

#include "stdafx.h"    // Includes "QuickOpc.h", and other commonly used files
#include <atlsafe.h>
#include "WriteMultipleValues.h"

namespace _EasyUAClient
{
    void WriteMultipleValues::TestSuccess()
    {
        // Initialize the COM library
        CoInitializeEx(NULL, COINIT_MULTITHREADED);
        {
            // Instantiate the client object
            _EasyUAClientPtr ClientPtr(__uuidof(EasyUAClient));

            _UAWriteValueArgumentsPtr WriteValueArguments1Ptr(_uuidof(UAWriteValueArguments));
            WriteValueArguments1Ptr->EndpointDescriptor->UrlString = 
                //L"http://opcua.demo-this.com:51211/UA/SampleServer";
                L"opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            WriteValueArguments1Ptr->NodeDescriptor->NodeId->ExpandedText = L"nsu=http://test.org/UA/Data/ ;i=10221";
            WriteValueArguments1Ptr->Value = 23456;

            _UAWriteValueArgumentsPtr WriteValueArguments2Ptr(_uuidof(UAWriteValueArguments));
            WriteValueArguments2Ptr->EndpointDescriptor->UrlString = 
                //L"http://opcua.demo-this.com:51211/UA/SampleServer";
                L"opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            WriteValueArguments2Ptr->NodeDescriptor->NodeId->ExpandedText = L"nsu=http://test.org/UA/Data/ ;i=10226";
            WriteValueArguments2Ptr->Value = L"This string cannot be converted to Double";

            _UAWriteValueArgumentsPtr WriteValueArguments3Ptr(_uuidof(UAWriteValueArguments));
            WriteValueArguments3Ptr->EndpointDescriptor->UrlString = 
                //L"http://opcua.demo-this.com:51211/UA/SampleServer";
                L"opc.tcp://opcua.demo-this.com:51210/UA/SampleServer";
            WriteValueArguments3Ptr->NodeDescriptor->NodeId->ExpandedText = L"nsu=http://test.org/UA/Data/ ;s=UnknownNode";
            WriteValueArguments3Ptr->Value = L"ABC";

            CComSafeArray<VARIANT> arguments(3);
            arguments.SetAt(0, _variant_t((IDispatch*)WriteValueArguments1Ptr));
            arguments.SetAt(1, _variant_t((IDispatch*)WriteValueArguments2Ptr));
            arguments.SetAt(2, _variant_t((IDispatch*)WriteValueArguments3Ptr));
            CComVariant vArguments(arguments);

            // Obtain values. By default, the Value attributes of the nodes will be Write.
            CComSafeArray<VARIANT> results;
            results.Attach(ClientPtr->WriteMultipleValues(&vArguments));
            
            // Display results
            for (int i = results.GetLowerBound(); i <= results.GetUpperBound(); i++)
            {
                _UAWriteResultPtr ResultPtr = results[i];

                if (ResultPtr->Succeeded)
                    _tprintf(_T("Result %d success\n"), i);
                else
                    _tprintf(_T("Result d: s\n"), i, (LPCTSTR)CW2CT(ResultPtr->Exception->GetBaseException()->Message));
            }
        }
         // Release all interface pointers BEFORE calling CoUninitialize()
        CoUninitialize();
    }
}

Python

# This example shows how to write values into 3 nodes at once, test for success of each write and display the exception
# message in case of failure.
#
# Find all latest examples here: https://opclabs.doc-that.com/files/onlinedocs/OPCLabs-OpcStudio/Latest/examples.html .
# OPC client and subscriber examples in Python on GitHub: https://github.com/OPCLabs/Examples-QuickOPC-Python .
# Missing some example? Ask us for it on our Online Forums, https://www.opclabs.com/forum/index ! You do not have to own
# a commercial license in order to use Online Forums, and we reply to every post.
# The QuickOPC package is needed. Install it using "pip install opclabs_quickopc".
import opclabs_quickopc

# Import .NET namespaces.
from OpcLabs.EasyOpc.UA import *
from OpcLabs.EasyOpc.UA.OperationModel import *


endpointDescriptor = UAEndpointDescriptor('opc.tcp://opcua.demo-this.com:51210/UA/SampleServer')
# or 'http://opcua.demo-this.com:51211/UA/SampleServer' (currently not supported)
# or 'https://opcua.demo-this.com:51212/UA/SampleServer/'

# Instantiate the client object
client = EasyUAClient()

print('Modifying values of nodes...')
writeResultArray = IEasyUAClientExtension.WriteMultipleValues(client, [
    UAWriteValueArguments(endpointDescriptor, UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10221'), 23456),
    UAWriteValueArguments(endpointDescriptor, UANodeDescriptor('nsu=http://test.org/UA/Data/ ;i=10226'),
                          'This string cannot be converted to Double'),
    UAWriteValueArguments(endpointDescriptor, UANodeDescriptor('nsu=http://test.org/UA/Data/ ;s=UnknownNode'), 'ABC'),
    ])

for i, writeResult in enumerate(writeResultArray):
    if writeResult.Succeeded:
        print('writeResultArray[', i, ']: success', sep='')
    else:
        print('writeResultArray[', i, '] *** Failure: ', writeResult.Exception.GetBaseException().Message, sep='')

print()
print('Finished.')

 

Write results

The WriteMultiple and WriteMultipleValues methods return an array of UAWriteResult objects. Besides the inherited members of OperationResult, such as the Exception, the UAWriteResult contains additional information that describes the outcome of the Write operation in case of success:

Advanced

If you access some node or nodes repeatedly, it might be possible to improve the performance of it by (pre-)registering the node or nodes with the server. The performance improvement will only occur if the target OPC UA server supports the necessary node registration services. For more information, see OPC UA Node Registration Service.

See Also